// 数据转换工具
import 'dart:convert';
// Material Design 设计
import 'package:flutter/material.dart';
// 需要在pubspec.yaml -> dependencies下添加依赖，并执行flutter packages get拉取包
import 'package:http/http.dart' as http;

/// 运行在主线城
class RunOnUiThreadApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '运行在主线程',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: RunOnUiThreadAppPage(),
    );
  }
}

/// 运行在主线程页面
class RunOnUiThreadAppPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => RunOnUiThreadAppPageState();
}

/// 运行在主线程页面状态
//class RunOnUiThreadAppPageState extends State<RunOnUiThreadAppPage> {
//  @override
//  Widget build(BuildContext context) {
//    return Scaffold(
//      appBar: AppBar(
//        title: Text("运行在主线程"),
//      ),
//      body: Center(
//        child: MaterialButton(
//          onPressed: _loadData,
//          child: Text('获取数据'),
//        ),
//      ),
//    );
//  }
//
//  /// 加载数据，并更新UI
//  _loadData() async {
//    // 设置网络链接
//    String dataURL = "https://jsonplaceholder.typicode.com/posts";
//    // 等待网络数据数据结果
//    http.Response response = await http.get(dataURL);
//    // 解析JSON数据
//    print(json.decode(response.body));
//  }
//}

/// 更新ListView
class RunOnUiThreadAppPageState extends State<RunOnUiThreadAppPage> {
  // 初始化列表
  List widgets = [];

  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Sample App"),
      ),
      body: ListView.builder(
        itemCount: widgets.length,
        itemBuilder: (BuildContext context, int position) {
          return getRow(position);
        },
      ),
    );
  }

  /// 获取列表条目
  Widget getRow(int position) {
    return Padding(
      padding: EdgeInsets.all(10.0),
      child: Text("Row ${widgets[position]["title"]}"),
    );
  }

  /// 加载数据
  loadData() async {
    String dataURL = "https://jsonplaceholder.typicode.com/posts";
    http.Response response = await http.get(dataURL);
    // 更新UI时需要使用setState
    setState(() {
      widgets = json.decode(response.body);
      print(widgets);
    });
  }
}
